--
-- Author: dbliu
-- Date: 2014-02-26 22:10:06
--

--=model=========================================================================================================
local EMBullet2 = import("..EM")

--=view=========================================================================================================
local EV = import("..EV")

local EVBullet2 = class("EVBullet2",EV)

function EVBullet2:ctor(model)

	EVBullet2.super.ctor(self,model)

	local cls = model.class

	--[[通过代理注册事件的好处：可以方便的在视图删除时，清理所有通过该代理注册的事件，
	同时不影响目标对象上注册的其他事件]]
	cc.EventProxy.new(model,self)
		:addEventListener(cls.CHANGE_STATE_EVENT, self.onStateChange_, self)
		:addEventListener(cls.START_EVENT, self.onStart, self)

end

function EVBullet2:onStateChange_(event)

end

function EVBullet2:onStart( event )
    local frames = display.newFrames("bullet%d.png", 2, 1)
	local animation = display.newAnimation(frames, 0.6 / 4)

	self.sprite_:playAnimationForever(animation)

	-- create body
    self.body_ = app.world:createBoxBody(10, 80,40)

    self.body_:setCollisionType(2+4)
    self.body_:setCollisionGroup(6)
    self.body_:setIsSensor(true)

    -- binding sprite to body
    self.body_:bind(self.sprite_)
    -- set body position
    self.body_:setPosition(event.x, event.y)

    self.body_:setVelocity(0,700)


end



--=controller=========================================================================================================

local EC = import("..EC")
local ECBullet2 = class("ECBullet1",EC)

function ECBullet2:ctor(x,y)

    self.model_ = EMBullet2.new({id = "bullet1"})
    

    self.views_ = EVBullet2.new(self.model_)
    :pos(display.left, display.bottom)
    :addTo(self)

    self.model_.fsm__:doEvent("start",x,y) 

    

    -- 注册帧事件
    self:addScriptEventListener(cc.Event.ENTER_FRAME, handler(self, self.tick))

--[[
    -- 在视图清理后，检查模型上注册的事件，看看是否存在内存泄露
    self:addScriptEventListener(cc.Event.CLEANUP, function()
        self.model_:getComponent("components.behavior.EventProtocol"):dumpAllEventListeners()
    end)
]]

end

function ECBullet2:tick( dt )

    self:checkLifeCycle()

    
end


function ECBullet2:checkLifeCycle()
    local p = self.views_:getSpritePosition()
    if p.x<display.left or p.x>display.right or p.y<display.bottom+app.flightDistance or p.y>display.top+app.flightDistance then
        self.views_.body_:removeSelf(true)
        self:removeSelf(true)
    end
end


return ECBullet2